'use strict';

const Service = require('egg').Service;
const md5 = require('md5');
const base64url = require('base64-url');

class AuthService extends Service {
  // 生成token串
  async getToken(name, identity) {
    const date = Date.now();
    const random = Math.random().toString(26);
    const res = base64url.encode(md5(date + random + name) + identity);
    return res;
  }

  // 插入一个新用户的登录信息,如果已存在，就删除，避免多点登录
  async insertOneAuth(token, userId, identity) {
    const { ctx, app } = this;
    await this.delUserAuth(userId);
    const auth_time = app.config.auth_time;
    const expire_time = Date.now() + auth_time;
    await ctx.model.Authorize.create({
      token,
      userId,
      identity,
      expire_time
    });

  }

  // 删除已有的用户的登录信息
  async delUserAuth(userId) {
    await this.ctx.model.Authorize.deleteOne({
      userId
    });
  }

  // 根据token查询登录认证信息,如果过期了就删除
  async checkAuth(token) {
    const res = await this.ctx.model.Authorize.findOne({ token });
    if (!res) {
      return {
        errcode: 1,
        msg: "找不到用户"
      };
    }
    if (res.expire_time < Date.now()) {
      this.delUserAuth(res.userId);
      return {
        errcode: -1,
        msg: "登录已过期"
      };
    }
    return {
      errcode: 0,
      msg: "message",
      data: res
    };
  }

  // 通过token拿到userId
  async getUserId(token) {
    const res = await this.ctx.model.Authorize.findOne({ token });
    if (res) {
      return res.userId;
    }
    return null;
  }
}

module.exports = AuthService;
